<?php

class set_favorite_handler extends _site_handler {
	public function __construct($m, $view) {
		$this->InitializeSite($m);

		if ( !isset($_GET['back_url']) ) $_GET['back_url'] = '/';

		if ( !$this->User ) {
			header("Location: " . $this->GetUrl('login', (($this->Ajax)?'ajax=1&':'') . 'back_url=' . urlencode($this->Url)));
			exit;
		}

		if (
			!isset($_GET['action']) || !($action = $_GET['action']) ||
			!isset($_GET['id'])     || !($id     = intval($_GET['id']))
		) {
			header("Location: " . $_GET['back_url']);
			exit;
		}

		if ( $action == 'add_favorite' ) {
			$query = "SELECT
							f.id
						FROM
							msnu_smileyfavorite AS f
						WHERE
							f.usr_id=" . $this->User->Id . " AND
							f.smiley_id=" . $id . "
						LIMIT
							1
							";

			$result = $this->GetResult($query);

			if ( $result && ($row = mysql_fetch_assoc($result)) && $row['id'] ) {
				$query = "UPDATE msnu_smileyfavorite SET enabled=1 WHERE id=" . $row['id'] . " LIMIT 1";
				$this->GetResult($query);
			} else {
				$query = "INSERT INTO msnu_smileyfavorite SET smiley_id=" . $id . ", usr_id=" . $this->User->Id . ", added=NOW(), enabled=1";
				$this->GetResult($query);
			}
		} elseif ( $action == 'remove_favorite' ) {
			$query = "UPDATE msnu_smileyfavorite SET enabled=0 WHERE smiley_id=" . $id . " AND usr_id=" . $this->User->Id . " LIMIT 1";
			$this->GetResult($query);
		}


		if ( !$this->Ajax ) {
			header("Location: " . $_GET['back_url']);
			exit;
		} else {
			$this->RenderViewContent($view);
		}
	}
}
